package com.lovo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

//设置为全局参数，做到无参spring
@Configuration
//定义扫描的路径,从中找出标识了需要装配的类自动装配到spring的bean容器中
@ComponentScan(basePackages = "com.lovo")
//开启aspectj注解功能，达成AOP的使用
@EnableAspectJAutoProxy(
        proxyTargetClass = true  //当自己定义了接口时，需要加入该属性
)
@MapperScan(basePackages = "com.lovo.dao") // 动态获取SqlMapper
// 中心配置类添加注解,开启事务管理
@EnableTransactionManagement
public class ApplicationConfig {
    @Bean
    public DataSource dataSource(DBProperties dbProperties){
//        alibaba的数据对象
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(dbProperties.getUrl());
        dataSource.setDriverClassName(dbProperties.getDriver());
        dataSource.setUsername(dbProperties.getUser());
        dataSource.setPassword(dbProperties.getPwd());
        // 添加数据连接池的配置
        return dataSource;
    }
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource, DBProperties dbProperties){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 设置数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 配置POJO类的别名
        sqlSessionFactoryBean.setTypeAliasesPackage(dbProperties.getTypeAliasesPackage());
        // 动态获取SqlMapper
        // PathMatchingResourcePatternResolver classPathResource = new PathMatchingResourcePatternResolver();
        // sqlSessionFactoryBean.setMapperLocations(classPathResource.getResources(propertiesConfig.getMapperLocations()));
        return sqlSessionFactoryBean;
    }
    // 创建事务管理器对象
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager =
                new DataSourceTransactionManager(dataSource);
    return dataSourceTransactionManager;
        }
    }
